var EventProxy = require('eventproxy');
var entity = require('../entity');
var Faction = entity.Faction;
var User = entity.User;
var relation = require('./relation');
var userProxy = require('./user');
var factionMemberProxy = require('./factionmember');
var redisManager = require('./redisManager');
var logger = require('../service/Logger');
var needle = require('needle');




exports.newAndSave = function(user, name, descrip, tags, csp, callback){
    User.findById(user.id, function(err, user){
        if(err) return callback(err);
        var faction = new Faction();
        faction.name = name;
        faction.description = descrip;
        faction.creator = user._id;
        faction.creditspolicy = csp?csp._id:null;
        faction.tags = tags;
        faction.save(function(err, faction){
            user.factions.push({
                id: faction._id.toHexString(),
                name: faction.name
            })
            // 创始人加入到圈子中
            user.save(function(err, userdata){
                factionMemberProxy.newAndSave(faction, user, user.card, function(err, fm){
                    if(err){
                        logger.error('user ['+user._id+'] join faction failed... ');
                    }
                    redisManager.addFactionMember(faction._id, user.id, function(err, resp){
                        logger.debug('user ['+user._id+'] join faction success! '+ resp);
                    })
                });
                if(err)
                    logger.error('['+user.name+'] not in faction ['+faction._id+']..');
                else
                    logger.debug('['+user.name+'] join faction ['+faction._id+']..');
            })
            callback(err, faction);
        })
    })
}

exports.findById = function(id, callback){
    Faction.findOne({_id: id})
        .populate('creator')
        .populate('creditspolicy')
        .exec(function(err, faction){
        callback(err, faction);
    })
}

exports.updateFaction = function(id, newFaction, callback){
    Faction.update({_id: id}, {$set: {
        name: newFaction.name,
        description: newFaction.description,
        tags: newFaction.tags
    }}, {}, function(err, resp){
        callback(err, resp)
    })
}

exports.findByCreator = function(user, callback){
    Faction.find({creator: user.id})
        .populate('creator')
        .sort({weight: -1})
        .exec(function(err, faction){
        callback(err, faction);
    })
}

exports.findByContainsUser = function(user, callback){
    Faction.find({$or: [{creator: user.id}, {members: {$elemMatch:{id: user.id}}}]})
        .populate('creator')
        .exec(function(err, factions){
        callback(err, factions);
    })
}

exports.updateMemberCount = function(factionId, count, callback){
    Faction.update({_id: factionId}, {$set: {memberCount: count}}, {}, function(err, data){
        callback(err, data);
    })
}

exports.tickAUserfromFaction = function(factionId, targetId, creatorId, callback){
    this.findById(factionId, function(err, faction){
        if(faction.creator._id.toHexString() === creatorId){
            var count = faction.memberCount;
            var ep = new EventProxy();
            ep.bind('error', function(err){
                logger.error(err);
                ep.unbind();
                callback(err);
            });
            ep.all('rmfm', 'rmuser', function(rmfm, rmuser){
                Faction.update({_id: factionId}, {$set: {memberCount: count-1}}, {}, function(err, data){
                    if(err) logger.error(err);
                    callback(err, data);
                })
            })
            factionMemberProxy.removeByUserIdFactionId(targetId, factionId, function(err, data){
                if(err) ep.emit('error', err);
                ep.emit('rmfm', data);
            });
            userProxy.removeFaction(targetId, factionId, function(err, data){
                if(err) ep.emit('error', err);
                ep.emit('rmuser', data);
            });
            //TODO: 移除faction member 缓存
        }else{
            callback({not:'no promission'});
        }
    })
}

exports.addUser2Faction = function(user, id, callback){
    var _self = this;
    var from = user.from;
    var ep = new EventProxy();
        ep.bind('error', function(err){
            if(err)
                logger.error(err.message);
            ep.unbind();
            return callback(err);
        });
    ep.all('user', 'faction', function(user, faction){
        redisManager.isInFaction(id, user.id, function(err, isIn){
            if(isIn){
                callback(null, {data: 'already'});
            }else{
                console.log('非圈内人');
                user.factions.push({
                    id: id,
                    name: faction.name
                });
                user.save(function(err, data){
                    if(err) return callback(err);
                    //faction 携带from
                    faction.from = from;
                    factionMemberProxy.newAndSave(faction, user, user.card, function(err, fm){
                        redisManager.addFactionMember(id, user._id, function(err, resp){// 加入圈子缓存
                            if(err) return callback(err)
                            logger.debug('User ['+user._id+'] join Faction ['+faction._id+'] from '+from);
                            //圈子内建立关系
                            _addMemberRelations(user._id, faction._id);
                            callback(err, fm);
                        });
                    });
                });
                _self.updateMemberActTopicCount(faction, 1, 0, 0, function(){
                    console.log('update faction counts ...')
                });
            }
        })
    });
    userProxy.getUserById(user.id, function(err, user){
        if(err) ep.emit('error', err);
        ep.emit('user', user);
    });
    Faction.findOne({_id: id}).exec(function(err, faction){
        if(err) ep.emit('error', err);
        ep.emit('faction', faction);
    })
}
exports.updateMemberActTopicCount = function(faction, userNum, actNum, topicNum, callback){
    faction.memberCount += userNum;
    faction.actCount += actNum;
    faction.topicCount += topicNum;
    faction.save(callback)
}
function _addMemberRelations(userId, factionId){
    var postData = {
        faction: 'faction',
        factionId: factionId,
        userId: userId
    }
    relationBuilder.send(postData);
}

exports.getAllFactions = function(callback){
    Faction.find().exec(function(err, factions){
        callback(err, factions);
    })
}

exports.deleteById = function(user, id, callback){
    Faction.findById(id, function(err, faction){
        console.log(user)
        console.log(faction)
        if(err) return callback(err);
        if(user.id == faction.creator){
            Faction.update({_id: faction._id}, {$set: {isDelete: true}}, {}, function(err, resp){
                callback(err, faction);
            })
        }else{
            callback(err, null)
        }
    })
}